import React, { Component } from 'react';
import { render } from 'react-dom';
import PropTypes from 'prop-types';
import { Icon } from 'antd';

import styles from './style.scss';
import Modals from '@components/Modals';

export default class FileDownloadDialog extends Component {
    static propTypes = {
        files: PropTypes.array.isRequired,
        onCancel: PropTypes.func,
    };

    static defaultProps = {
        onCancel: () => undefined,
    };

    render() {
        const props = this.props;
        if (!props.files || props.files.length < 1) {
            return;
        }
        return (
            <Modals
                title="文件列表"
                visible={true}
                width={500}
                onCancel={props.onCancel}
                footer={null}
                maskClosable={false}
                destroyOnClose={true}
                getContainer={props.container}
            >
                <div className={styles.uploadedFileList}>
                    {
                        props.files.map((file, idx) => {
                            const {
                                name,
                                download,
                            } = file;
                            return (
                                <div className={styles.uploadedFile} key={download} title={name}>
                                    <div className={styles.uploadedFileName}>
                                        <a href={`${download}?name=${name}`} target="_blank" >
                                            <Icon type="paper-clip" />
                                            {name}
                                        </a>
                                    </div>
                                    <a
                                        className={styles.btnDeleteUploadedFile}
                                        href={`${download}?name=${name}`}
                                        target="_blank"
                                    >下载</a>
                                </div>
                            );
                        })
                    }
                </div>
            </Modals>
        );
    }
}

FileDownloadDialog.open = (files) => {
    if (!files) {
        return;
    }
    if (typeof files === 'string') {
        try {
            files = JSON.parse(files);
        } catch (err) {
            files = null;
        }
    } else if (!Array.isArray(files)) {
        files = [files];
    }
    if (!files || files.length < 1) {
        return;
    }
    const div = document.createElement('div');
    document.body.appendChild(div);
    const onCancel = () => {
        document.body.removeChild(div);
    }
    render(
        <FileDownloadDialog
            files={files}
            onCancel={onCancel}
            container={() => { return div }}
        />, div
    );
};